#!/usr/bin/env python3
"""
Media Create GUI - Application Startup Script
AI多模态内容生成平台 - 应用启动脚本
"""

import asyncio
import logging
import sys
import signal
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from src.media_create.main import app
from src.media_create.core.config import settings
from src.media_create.core.logging import setup_logging
from src.media_create.services.health_check_service import health_check_service
from src.media_create.services.cleanup_service import async_cleanup_service

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


class ApplicationManager:
    """应用管理器"""
    
    def __init__(self):
        self.is_running = False
        self.cleanup_tasks = []
    
    async def start(self):
        """启动应用"""
        try:
            logger.info("=" * 60)
            logger.info(f"启动 {settings.app_name} v{settings.app_version}")
            logger.info(f"环境: {settings.app_env}")
            logger.info(f"数据库: {settings.database.url.split('@')[-1] if '@' in settings.database.url else settings.database.url}")
            logger.info("=" * 60)
            
            # 设置结构化日志
            setup_logging()
            
            # 启动清理服务
            logger.info("启动清理服务...")
            await async_cleanup_service.start_cleanup_scheduler()
            
            self.is_running = True
            logger.info("应用管理器启动完成")
            
        except Exception as e:
            logger.error(f"启动失败: {e}")
            raise
    
    async def stop(self):
        """停止应用"""
        try:
            logger.info("正在停止应用...")
            self.is_running = False
            
            # 停止清理服务
            logger.info("停止清理服务...")
            await async_cleanup_service.stop_cleanup_scheduler()
            
            logger.info("应用管理器停止完成")
            
        except Exception as e:
            logger.error(f"停止失败: {e}")
    
    async def health_check(self) -> bool:
        """健康检查"""
        try:
            health_status = await health_check_service.get_health_status()
            is_healthy = health_status.get("overall_health", False)
            
            if is_healthy:
                logger.info("✅ 系统健康检查通过")
            else:
                logger.warning("⚠️  系统健康检查未通过")
                logger.warning(f"健康状态: {health_status}")
            
            return is_healthy
            
        except Exception as e:
            logger.error(f"健康检查失败: {e}")
            return False


async def main():
    """主函数"""
    app_manager = ApplicationManager()
    
    try:
        # 启动应用管理器
        await app_manager.start()
        
        # 运行健康检查
        is_healthy = await app_manager.health_check()
        
        if not is_healthy:
            logger.warning("系统未完全健康，但继续启动...")
        
        # 启动FastAPI应用
        logger.info("启动FastAPI应用...")
        logger.info(f"应用将在 http://{settings.host}:{settings.port} 运行")
        logger.info(f"API文档: http://{settings.host}:{settings.port}/docs")
        logger.info(f"健康检查: http://{settings.host}:{settings.port}/health")
        logger.info(f"详细健康检查: http://{settings.host}:{settings.port}/health/detailed")
        
        # 这里可以添加实际的FastAPI启动逻辑
        # 例如使用uvicorn启动
        import uvicorn
        
        config = uvicorn.Config(
            "src.media_create.main:app",
            host=settings.host,
            port=settings.port,
            log_level="info",
            access_log=True,
            reload=settings.is_development,
        )
        
        server = uvicorn.Server(config)
        
        # 设置信号处理
        def signal_handler(sig, frame):
            logger.info("接收到停止信号，正在关闭应用...")
            asyncio.create_task(app_manager.stop())
            sys.exit(0)
        
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
        
        # 启动服务器
        await server.serve()
        
    except KeyboardInterrupt:
        logger.info("用户中断，正在关闭应用...")
    except Exception as e:
        logger.error(f"应用运行错误: {e}")
        raise
    finally:
        # 清理资源
        await app_manager.stop()


def print_banner():
    """打印启动横幅"""
    banner = f"""
╔══════════════════════════════════════════════════════════════╗
║                    Media Create GUI                        ║
║              AI多模态内容生成平台                          ║
║                                                              ║
║  版本: {settings.app_version:<45} ║
║  环境: {settings.app_env:<45} ║
║  数据库: {settings.database.url.split('@')[-1][:42] if '@' in settings.database.url else settings.database.url[:42]:<42} ║
║                                                              ║
║  🚀 功能特性:                                                ║
║  • 多模型AI支持 (豆包、阿里云、OpenAI)                    ║
║  • 多模态内容生成 (图像、视频、音频、文本)               ║
║  • 异步任务处理系统                                        ║
║  • 桌面GUI客户端                                           ║
║  • RESTful API接口                                         ║
║                                                              ║
╚══════════════════════════════════════════════════════════════╝
"""
    print(banner)


if __name__ == "__main__":
    print_banner()
    
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("应用被用户中断")
    except Exception as e:
        logger.error(f"应用启动失败: {e}")
        sys.exit(1)